package com.kob.backend.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.account.LoginService;
import com.kob.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, String> getToken(String username, String password) {
        System.out.println(username);

        UserDetailsImpl loginUser;
        User user;

        // 判断输入的内容是用户名还是手机号
        if (username.matches("^\\d{11}$")) {
            // 如果是手机号，根据手机号查询用户信息
            QueryWrapper<User> queryWrapper= new QueryWrapper<>();
            queryWrapper.eq("phone", username);
            user = userMapper.selectOne(queryWrapper);
        } else {
            // 如果是用户名，根据用户名查询用户信息
            QueryWrapper<User> queryWrapper= new QueryWrapper<>();
            queryWrapper.eq("username", username);
            user = userMapper.selectOne(queryWrapper);
        }

        if (user == null) {
            // 用户不存在
            throw new UsernameNotFoundException("用户不存在");
        }


        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(), password);

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);  // 登录失败，会自动处理
//        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
        loginUser = (UserDetailsImpl) authenticate.getPrincipal();
//        User user = loginUser.getUser();
        String jwt = JwtUtil.createJWT(user.getId().toString());

//        System.out.println(user.getId().toString());

        Map<String, String> map = new HashMap<>();
        map.put("error_message", "success");
        map.put("token", jwt);

        return map;
    }
}
